<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
    img {
      display: block;
      width: 400px;
      height: 400px;
    }
  </style>
</head>
<body>
<div class="container">
  <img src="../image/star.gif" alt="" data-src="../image/banner1.jpg">
  <img src="../image/star.gif" alt="" data-src="../image/banner2.jpg">
  <img src="../image/star.gif" alt="" data-src="../image/banner3.jpg">
  <img src="../image/star.gif" alt="" data-src="../image/banner4.jpg">
  <img src="../image/star.gif" alt="" data-src="../image/banner5.jpg">
  <img src="../image/star.gif" alt="" data-src="../image/banner6.jpg">
  <img src="../image/star.gif" alt="" data-src="../image/banner7.jpg">
  <img src="../image/star.gif" alt="" data-src="../image/banner8.jpg">
</div>
<script>
  let imgDom = document.getElementsByTagName('img')
  let imgLength = imgDom.length

  let n = 0
  lazyLoad()
  // 滚动事件
  window.onscroll = lazyLoad
  function lazyLoad() {
    // 获取屏幕高度
    let screenHeight = document.documentElement.clientHeight
    // 获取滚动条高度
    let scrollTop = document.documentElement.scrollTop || document.body.scrollTop

    for (let i = n; i < imgLength; i++) {
      // 获取图片距离顶部的高度
      let imgTop = imgDom[i].offsetTop
      // 判断图片是否在可视区域内
      if (imgTop < screenHeight + scrollTop) {
        console.log("渲染第", i + 1, '张图片')
        // 将data-src的值赋给src
        imgDom[i].src = imgDom[i].getAttribute('data-src')
        // 渲染过的图片不用再处理 从下一张将要处理的图片开始
        n = i + 1
      }
    }
  }
</script>
</body>
</html>
